package cn.juc;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicIntegerArray;

/**
 * @author xzh
 * 数据库连接池
 */
@Slf4j
public class ConnectionPoolTest {
    public static void main(String[] args) throws InterruptedException {
        ConnectionPool pool=new ConnectionPool(2);
        for (int i = 0; i <5 ; i++) {
            new Thread(()->{
                Connection connection=pool.borrow();
                try {
                    Thread.sleep(1000);
                    pool.free(connection);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
@Slf4j
class ConnectionPool{
    private final int poolsize;
    private Connection[] connections;
    //状态 0-空闲 1-》满
    private AtomicIntegerArray status;
    //初始化大小
    public ConnectionPool(int size){
        this.poolsize=size;
        connections=new Connection[size];
        status=new AtomicIntegerArray(new int[size]);
        //log.info(String.valueOf(status.get(1)));
        //log.info(String.valueOf(status.get(0)));
        for (int i = 0; i <poolsize ; i++) {
            connections[i]=new Connection();
            log.info("初始化一次"+connections[i]);
        }
    }
    //借用连接
    public Connection borrow(){
        while (true){
            //log.info("66666");
            for (int i = 0; i <poolsize ; i++) {
               if (status.get(i)==0){ //存在空闲连接
                   log.info(String.valueOf(status.get(i)));
                   if (status.compareAndSet(i,0,1)){ //使用种
                       log.info("线程借用连接中");
                       return connections[i];
                   }
               }
            }
            //没有空闲的连接就等待归还唤醒
          synchronized (this){
              try {
                  this.wait();
                  log.info("等待归还唤醒");
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }

          }
        }
    }
    public void free(Connection connection){
        for (int i = 0; i <poolsize ; i++) {
            if (connections[i]==connection){
                status.set(i,0);//空闲状态
                log.info("连接归还成功");
                break;
            }
        }
        synchronized (this){
            this.notifyAll();
        }
    }
}
class Connection{}

